package com.rfid.socketio;

import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class InWriteableStream1 extends InputStream {
    private final BlockingQueue<Byte> queue;

    public InWriteableStream1() {
        this.queue = new LinkedBlockingQueue<>(100*1024);
    }

    public void writeBytes(byte[] bytes) throws IOException {
        System.out.println("writeBytes size = " + bytes.length);
        for (byte b : bytes) {
            write(b);
        }
    }

    public void write(int b) throws IOException {
        byte value = (byte) b;
        try {
            // 将数据放入队列，如果队列已满则阻塞等待空间可用
            queue.put(value);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new IOException("Interrupted while writing to the queue", e);
        }
    }

    public int read() throws IOException {
        try {
            // 从队列中获取数据，如果队列为空则阻塞等待数据可用
            return queue.take()&0xff;
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new IOException("Interrupted while reading from the queue", e);
        }
    }

    public int size() {
        return queue.size();
    }
}
